//
//  VVOAuthViewController.swift
//  Weibo
//
//  Created by 王惠平 on 2017/3/28.
//  Copyright © 2017年 Will Wang. All rights reserved.
//

import UIKit
import SVProgressHUD

//微博AppKey
let AppKey = "2855421214"

//授权回调页地址
let uri = "http://www.163.com"

//微博的appSecret
let AppSecret = "6949efffbdac601dd693760d6a56d8a1"


class VVOAuthViewController: UIViewController {
    
    
//    https://api.weibo.com/oauth2/authorize?client_id=2855421214&redirect_uri=http://adrianwhp@163.com
    
  
    //懒加载
    private lazy var webView: UIWebView = UIWebView()
    
    //自定义视图控制器
    override func loadView() {
        
        //遵守代理
        webView.delegate = self
        
        view = webView
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()

        
        setupUI()
        requestOAuth()
    }
    
    //加载微博登录界面
   private func requestOAuth() {
    
    //请求地址
    let url = URL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(uri)")
    
    print(url ?? "请求url失败")
    
    //请求对象
    let urlRequest = URLRequest(url: url!)
    
    //加载web页面
    webView.loadRequest(urlRequest)
    
    
    }

   private func setupUI() {
        
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
    
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动添加", target: self, action: #selector(autoFillAction))
    
    navigationItem.title = "微博登录"
    
    }
    
    @objc private func cancelAction() {
        
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func autoFillAction() {
        
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = 'hao123guohaibin@163.com';document.getElementById('passwd').value = 'guohaibin123';")
        
    }
    
//    //通过code获取accesstoken
//    fileprivate func requestAccessToken(code: String) {
//        
//       VVNetworkTools.sharedTools.requestAccessToken(code: code) { (response, error) in
//        
//        if error != nil {
//            
//            print("网络请求异常:\(error!)")
//            
//            return
//        }
//        
//        //print(response);
//        guard let dic = response as? [String: Any] else {
//            
//            print("服务器端数据不对")
//            
//            return
//        }
//        
//        //代码执行到此表示oc对象
//        print(dic)
//        
//        let userAccount = VVUserAccount(dic: dic)
//        
//       //通过uid和accessToken获取用户数据
//        self.requestUserInfo(userAccount: userAccount)
//        
//        }
//        
//    }
//    
//    fileprivate func requestUserInfo(userAccount: VVUserAccount) {
//        
//        //获取令牌
//        let accessToken = userAccount.access_token!
//        
//        //用户id
//        let uid = userAccount.uid
//        
//        VVNetworkTools.sharedTools.requestUserInfo(accessToken: accessToken, uid: uid) { (response, error) in
//            
//            if error != nil {
//                
//                print("网络请求异常:\(error!)")
//                
//                return
//            }
//            
//            
//            guard let dic = response as? [String: Any] else {
//                
//                print("服务端数据格式不对")
//                
//                return
//            }
//            
//            //给对象里面的name和头像赋值
//            let name = dic["name"] as? String
//            
//            let avatar_large = dic["avatar_large"] as? String
//            
//            userAccount.name = name
//            
//            userAccount.avatar_large = avatar_large
//            
//            //print(userAccount.name, userAccount.avatar_large)
//        
//        
//            //保存用户对象
//            userAccount.saveUserAccount()
//        }
//        
//        
//        
//    }
//  
}

//实现代理方法
extension VVOAuthViewController:UIWebViewDelegate {
    
    //将要加载网络请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //获取请求地址
        guard let urlStr = request.url?.absoluteString else {
            
            //如果请求地址是nil,不需要进行加载
            return false
        }
        
        if !urlStr.hasPrefix(uri) {
            
            return true
        }
        
        //代码执行到此表示是我们关心的回调地址,query表示请求的参数
        if let query = request.url?.query, query.hasPrefix("code=") {
            
            print(query)
            //授权码code=2603b0342aebeb820b8c4136345c6b5a
            
            //截取授权码(code)
            let code = query.substring(from: "code=".endIndex)
            
//            requestAccessToken(code: code)
            //通过viewModel实例化调用获取accessToken
            VVUserAccountViewModel.sharedViewModel.requestAccessToken(code: code, callBack: { (isSuccess) in
                
                if isSuccess {
                    
                    print("登录成功")
                    
                    //进入欢迎页面
                    //先把当前OAuth控制器dismiss
                    self.dismiss(animated: false, completion: { 
                        
                        //需要等到dismiss操作完成以后再去发送切换根视图控制器的通知,否则会有内存泄漏
                        //发送切换根视图的通知
                        NotificationCenter.default.post(name:NSNotification.Name(SwitchRootVCNotification), object: self)
                        
                    })
                    
                    
                    
                } else {
                    
                    print("登录失败")
                }
            })
            
        } else {
            
            //点击取消授权
            dismiss(animated: true, completion: nil)
        }
        
        //print(urlStr)
        return false
    }
    



    //已经开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        //显示等待指示视图
        SVProgressHUD.show()
    }
    
    //加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        //移除等待指示视图
        SVProgressHUD.dismiss()
    }
    
    //加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
        //移除等待指示视图
        SVProgressHUD.dismiss()
    }
    
}
